package com.interview.a_多线程.c_停止线程.g_停止线程_最佳实践.b_恢复中断;

/**
 * 恢复中断
 * <p>
 * 消化InterruptException异常后
 * 重新发起中断
 * 这样后续的执行才能检查到发生了中断
 */

public class StopThread implements Runnable {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new StopThread());
        thread.start();

        //执行0.5秒时中断
        Thread.sleep(3000);
        thread.interrupt();
    }

    @Override
    public void run() {
        int count = 0;
        System.out.println("Thread.currentThread().isInterrupted()---> " + Thread.currentThread().isInterrupted());
        while (count <= 1000) {
            if (Thread.currentThread().isInterrupted()) {
                System.out.println("run ：记录日志.........");
                System.out.println("run ：执行中断.........");
                break;
            }

            if (count % 10 == 0) {
                System.out.println(count + "  是10的倍数");
            }
            exceptionA();
            count++;
        }

        System.out.println("任务运行结束...  当前 interrupt=" + Thread.currentThread().isInterrupted());
    }

    /**
     * 方法必须消化异常，且不抛出
     * <p>
     * 所以需要恢复中断（重新发起中断）
     * 以便
     */
    private void exceptionA() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.out.println("exceptionA ：内部消化掉中断.....");
            System.out.println("exceptionA ：保存日志。。。。。。");
            e.printStackTrace();

            System.out.println("exceptionA ：重新恢复中断.....");
            Thread.currentThread().interrupt();
        }
    }
}
